import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws Exception {
        HttpRequest req = HttpRequest.builder()
                .url("https://api.github.com/users/kimi")
                .method("GET")
                .header("Accept", "application/json")
                .header("User-Agent", "kimi-demo")
                .build();

        System.out.println(req);
    }
}

// 当对象字段多、组合多、顺序随意，还想不可变时，
// Builder = 可读 + 易扩展 + 类型安全 + 不可变，
// “把对象创建过程拆成两步：先自由拼装，再一次性冻结”；避免构造地狱（多个构造重载）
final class HttpRequest {
    private final String url;
    private final String method;
    private final Map<String, String> headers;
    private final String body;

    private HttpRequest(Builder b) { // 私有，强制走 Builder
        this.url = b.url;
        this.method = b.method;
        this.headers = Map.copyOf(b.headers); // 不可变
        this.body = b.body;
    }

    /* ======== 只读 getter ========= */
    public String url() {
        return url;
    }

    public String method() {
        return method;
    }

    public Map<String, String> headers() {
        return headers;
    }

    public String body() {
        return body;
    }

    @Override
    public String toString() {
        return method + " " + url + " | headers=" + headers + " | body=" + body;
    }

    /* ======== 静态工厂：入口 ======== */
    public static Builder builder() {
        return new Builder();
    }

    /* ======== 真正的 Builder ======== */
    public static class Builder {
        private String url;
        private String method = "GET"; // 默认值
        private Map<String, String> headers = new HashMap<>();
        private String body;

        public Builder url(String url) {
            this.url = url;
            return this;
        }

        public Builder method(String m) {
            this.method = m;
            return this;
        }

        public Builder header(String k, String v) {
            this.headers.put(k, v);
            return this;
        }

        public Builder body(String body) {
            this.body = body;
            return this;
        }

        public HttpRequest build() {
            if (url == null)
                throw new IllegalStateException("url required");
            return new HttpRequest(this);
        }
    }
}